
import React from 'react'
import { connect }  from 'react-redux';

import * as BillLineAction from '../../actions/BillLineAction'
import * as UnitAction  from '../../actions/UnitAction';

class WorkBillEdit extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {}
    }
  }

  componentDidMount() {
    this.$unitList = $(ReactDOM.findDOMNode(this.refs.unitLists));
  }

  componentWillReceiveProps(props) {
    var data = props.data;
    if(!data.id){
      var date = new Date();
      //
      // data['year'] = date.getFullYear();
      // data['month'] = date.getMonth();
      if (!data.year) {
        data.year = date.getFullYear();
      }
      if (!data.month) {
        data.month = date.getMonth();
      }
    }
    // console.log(data)
    this.setState({
      data: data
    })
  }

  componentDidUpdate() {
    if(this.props.lines){
      this.props.onPushBillLineData(this.props.lines);
    }

    var units = this.props.units;
    var self = this;
    if (units && units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        this.$unitList.hide();
      }else if (!this.state.data.unit.unit_desc || this.state.data.unit.unit_desc.trim() == ''){
        this.$unitList.hide();
      }
      else {
        this.$unitList.show();
      }
    }else {
      this.$unitList.hide();
    }

  }

  onDataSubmit() {
    var data = this.state.data;
    this.props.onDataCreate(data);
  }

  onSelectUnitClick() {
    this.props.onSelectUnitClick();
  }

  onCreateBillLineClick(billId){
    this.props.onCreateBillLineClick(billId);
  }

  onChange(event, key) {
    var value = $(event.target).val();
    var data = this.state.data;
    data[key] = value;
    this.setState({
      data: data
    })
  }

  onUnitNumberChange(event) {
    var value = $(event.target).val();
    var data = this.state.data;
    var unit = data.unit;
    if (!unit) {
      unit = {};
    }
    unit.unit_desc = value;
    data.unit = unit;
    this.setState({
      data: data,
      showList: true
    })
    this.props.dispatch(
      UnitAction.loadUnitsAsync({unit_desc: value})
    )
  }

  onUnitNumberClick(unitList) {
    var value = unitList.unit_desc;
    var data = this.state.data;
    var unit = data.unit;
    if (!unit) {
      unit = {};
    }
    unit.unit_desc = value;
    data.unit_id = unitList.id;
    data.unit = unit;
    this.setState({
      data: data,
      showList: false
    })
  }

  onBillLinePay(data) {
    this.props.onWorkBillLineRemarkShow(data)
  }

  renderAddPropertyLine() {
    var self = this;
    if(this.state.data.property_bill_lines){
      // console.log(this.state.data.property_bill_lines)
      return this.state.data.property_bill_lines.map(function(data,index) {
        let remark = data.remark,
            sys_user = (data.sys_user&&data.sys_user.id)?data.sys_user.first_name+data.sys_user.last_name+": ": ""
        let pay_date = new Date(data.pay_date)
        if (pay_date != 'Invalid Date' && data.pay_date) {
          pay_date = pay_date.getFullYear()+"/"+(pay_date.getMonth()+1)+"/"+(pay_date.getDate())
                    +" "+pay_date.getHours()+":"+pay_date.getMinutes()
        }
        else {
          pay_date = ""
        }
        return (
          <tr id={data.id}>
            <td>{data.description}</td>
            <td>{data.gross_amount?parseFloat(data.gross_amount).toFixed(2):""}</td>
            <td>{data.wechat_trade_no}</td>
            <td>{pay_date}</td>
            <td>{data.is_pay?"已支付":"未支付"}</td>
            <td>
              {
                // {data.is_pay?false:<a onClick={(event)=>self.props.onDeleteLineClick(index)}>删除</a>}
              }
              {
                // data.is_pay?false:<a className="edit" onClick={(event)=>self.props.onEditLineClick(index)}>编辑</a>
              }
              {
                data.is_pay?<p>{sys_user+remark}</p>:""
                // data.is_pay?<a className="edit" onClick={(event)=>self.props.onBillLineRemarkShow(data)}>备注</a>:<a className="edit" onClick={(event)=>self.props.onBillLineRemarkShow(data)}>确定支付</a>
                // data.is_pay?<p>{sys_user+remark}</p>:<a className="edit" onClick={(event)=>self.props.onWorkBillLineRemarkShow(data)}>确定支付</a>
              }
            </td>
          </tr>
        )
      })
    }
    return "";
  }

  renderUnitList() {
    var units = this.props.units
    var self = this;
    if (units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        return ""
      }else if (!this.state.data.unit.unit_desc || this.state.data.unit.unit_desc.trim() == ''){
        return ""
      }
      else {
        return units.data.map(function(data) {
          return (
            <li className="list-group-item"
                onClick={(event)=>self.onUnitNumberClick(data)}>{data.unit_desc}</li>
          )
        })
      }
    }else {
      return "";
    }
  }


  render() {
    var self = this;
    var print_date = self.state.data.print_date;
    var print = print_date?(new Date(print_date)).toLocaleTimeString():"";
    // console.log(this.state.data.unit_id)
    var unit_desc = "";
    if (self.state.data.unit && self.state.data.unit.length > 0) {
      unit_desc = self.state.data.unit[0].unit_desc
    }
    return (
      <div className="modal fade" id="WorkBillEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="bill-modal-label">账单</h4>
            </div>
            <div className="modal-body">
            <div className="form-group">
              <label for="bill-number">账单号</label>
              <input ref="billNumber" type="text" className="form-control" readOnly
                      id="bill-number" placeholder="账单号自动生成" value={self.state.data.bill_number}
                      onChange={(event)=>this.onChange(event, "bill_number")}/>
            </div>
              <div className="form-group">
                <label for="bill-unit-id">户号</label>
                <input ref="billUnitId" type="hidden" className="form-control"
                        id="bill-unit-id" placeholder="户号" value={self.state.data.unit_id}
                        onChange={(event)=>this.onChange(event, "unit_id")}/>
                <input ref="billNuitNumber" type="text" className="form-control"
                        id="bill-unit-number" placeholder="户号"
                        value={unit_desc}
                        onChange={(event)=>this.onUnitNumberChange(event)} readOnly/>
                <div className="unit-lists" ref="unitLists">
                  <ul className="list-group">
                    {this.renderUnitList()}
                  </ul>
                </div>
              </div>
              <div className="form-group">
                <label for="bill-year">年</label>
                {this.props.isEdit?<input ref="billYear" type="text" className="form-control" readOnly
                        id="bill-year" placeholder="年" value={self.state.data.year}
                        onChange={(event)=>this.onChange(event, "year")}/>
                        :<input ref="billYear" type="text" className="form-control"
                                id="bill-year" placeholder="年" value={self.state.data.year}
                                onChange={(event)=>this.onChange(event, "year")}/>}
              </div>

              <div className="form-group">
                <label for="bill-month">月</label>
                {this.props.isEdit?
                  <input ref="billMonth" type="text" className="form-control" readOnly
                        id="bill-month" placeholder="月" value={self.state.data.month}
                        onChange={(event)=>this.onChange(event, "month")}/>
                  :<input ref="billMonth" type="text" className="form-control"
                          id="bill-month" placeholder="月" value={self.state.data.month}
                          onChange={(event)=>this.onChange(event, "month")}/>}
              </div>
              <div className="form-group">
                <label for="bill-is-push">是否已推送</label>
                <input ref="billIsPush" type="text" className="form-control" readOnly
                        id="bill-is-push" placeholder="是否已推送" value={self.state.data.is_push}
                        onChange={(event)=>this.onChange(event, "is_push")}/>
              </div>
              {
                // <div className="form-group">
                //   <label for="bill-print-date">打印时间</label>
                //   <input ref="billPrintDate" type="text" className="form-control" readOnly
                //           id="bill-print-date" placeholder="自动生成" value={print}
                //           onChange={(event)=>this.onChange(event, "print_date")}/>
                // </div>
              }

              <div className="form-group">
                <label for="bill-line">账单行</label>
                {
                  // <button type="button" onClick={(event)=>this.onCreateBillLineClick(self.state.data.id)}><span className="glyphicon glyphicon-plus"></span></button>
                }
                <div className="bill-line">
                  <table ref="billLine" className="table table-bordered">
                    <thead>
                      <tr>
                        <th>描述</th>
                        <th>总额</th>
                        <th>微信支付订单号</th>
                        <th>支付日期</th>
                        <th>状态</th>
                        <th>支付详情</th>
                      </tr>
                    </thead>
                    <tbody>
                          {self.renderAddPropertyLine()}
                    </tbody>
                  </table>
                </div>
              </div>

              <input ref="billId" value={self.props.data.id} hidden/>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-default" data-dismiss="modal">取消</button>
              {
                !this.props.isEdit?<button type="button" className="btn btn-primary"
                      onClick={(event)=> this.onDataSubmit()}>保存</button>: false
              }
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  // console.log("........")
  // console.log(state.billLines);
  return {
          lines: state.billLines ,
          units: state.units
          }
}

export default connect(mapStateToProps)(WorkBillEdit);
